/**
 * Created by w2ex on 7/21/16.
 */

'use strict'

import { EventEmitter } from 'events'
import map from 'lodash/map'
import ajax from '../utilities/ajax'
import api from '../configs/api'
import DialogControl from '../components/Dialog/actions'

const _codeHandlers = {

    '1008': () => {
        return false
    },
    '1009': () => {
        return false
    },
    '-1': (res) => {
        DialogControl.notify(res.msg)
        return true
    }

}

const _onApiSuccess = res => {

    try {
        if (!res.success) {
            if (!(res.code in _codeHandlers)) {
                DialogControl.notify(res.msg)
                return true
            }
            return _codeHandlers[res.code].call(null, res)
        }
    } catch (error) {
        return false
    }
    return true

}

const _onApiError = () => {
    return true
}

export default class Store extends EventEmitter {
    constructor() {
        super()
    }

    static apiGetJSON(action, query = {}) {

        const apiUrl = api.getURL(action)
        query = Object.assign({}, query)

        return ajax.getJSON(apiUrl, query, {
            cors: true,
            onSuccess: _onApiSuccess,
            onError: _onApiError
        })

    }

    static apiPost(action, data = {}) {

        const apiUrl = api.getURL(action)
        data = Object.assign({}, data)

        return ajax.post(apiUrl, data, {
            cors: true,
            onSuccess: _onApiSuccess,
            onError: _onApiError
        })

    }

    static makeListFromCollection(collection, field = '') {

        return map(collection, item => {
            return field ? item[field] : item
        })

    }
}
